0

私の問題は、現在作成中の顧客サービス データベースにあります。私はSQLクエリについて十分な知識がなく、クエリを正しく行うのに本当に苦労しています.

私は2つのテーブルを持っています:

**Customers:**
idcustomer
company_name
tel_number
address
postcode

**customer_machines**
id_customer_machine
id_customer
date_last_service
date_service_due

特定の日付セットの間でサービスの期限が切れているマシンを示す結果を選択したいと考えています (たとえば、マシンの期限は 9 月です)。

SELECT customer_machines.* from customer_machines WHERE (customer_machines.date_next_service BETWEEN '2013-09-01' AND '2013-10-01') ORDER BY date_next_service ASC;

これは問題ありませんが、一部の顧客は複数のマシンを持っています。

+---------------------+-------------+-------------------+-------------------+
| id_customer_machine | id_customer | date_last_service | date_next_service |
+---------------------+-------------+-------------------+-------------------+
|                   1 |           1 | 2012-09-02        | 2013-09-02        |
|                   2 |           2 | 2012-09-14        | 2013-09-14        |
|                   3 |           3 | 2012-09-30        | 2013-09-30        |
|                   5 |           3 | 2012-09-30        | 2013-09-30        |
+---------------------+-------------+-------------------+-------------------+

顧客が所有するマシンをグループ化し、顧客の詳細を結合して、ブラウザーのテーブルに次のように出力する必要があります。

Customer 1     address of customer 1     tel of customer 1     postcode of customer 1
machine-id-1                                 date-last-service      date-next-service
------------------------------------------------------------------------------------
customer 2     address of customer 2     tel of customer 2     postcode of customer 2
machine-id-2                                 date-last-service     date-next-service
-------------------------------------------------------------------------------------
customer 3     address of customer 3     tel of customer 3     postcode of customer 3
machine-id-3                                date-last-service     date-next-service
machine-id-5                                date-last-service     date-next-service

単一のクエリでこのように結果をまとめることはできますか? これまでのところ、私はphpでクエリをネストしようとしましたが、成功しませんでした。

あなたが私を正しい方向に向けることができれば、それは素晴らしいことです

ありがとう

4

3 に答える 3

0

SQL には、ネストされた結果を構築する機能はなく、単純なテーブルのみです。いくつかの単純なケースでは、 を使用GROUP_CONCATして値を連結できます。例えば:

SELECT 
  id_customer, 
  GROUP_CONCAT(id_customer_machine SEPARATOR ', ') as id_customer_machines
FROM customer_machines;

あなたを出力します:

+-------------+----------------------+
| id_customer | id_customer_machines |
+------------------------------------+
|           1 |                    1 |
|           2 |                    2 |
|           3 |                 3, 5 | 
+-------------+----------------------+

ただし、複数の列をグループ化する必要があるため、これは役に立ちません。あなたの場合、2つのオプションがあります:

  1. すべての顧客 ID を取得し、それらを繰り返し処理して、id_customer ごとに顧客のマシンを取得します。単純ですが、効率的ではありません (numCustomers + 1 クエリ)。
  2. データベースからプレーンデータを取得し、PHP を使用して構造化配列を作成します。効率的ですが、より多くのコーディング。
于 2013-08-02T10:43:00.793 に答える