MySQL JOIN两个表(联盟)

时间:2015-06-10 18:16:10

标签: mysql sql join

我有两个MySQL表

第一个是预订

$firebaseArray.$add

第二个是设置

+------------+--------------+---------+
| id         | contact_no   | date    | 
+------------+--------------+---------+
| p1         | 7898787946   | 15-06-05|
| p1         | 7897891562   | 15-06-05|
| p1         | 1546879585   | 15-06-07|
| p2         | 1789546528   | 15-06-07|
| p3         | 7894668265   | 15-06-07| 
+------------+--------------+---------+

我需要为特定的id连接两个表(让我们说p1),我想完全生成这个表。 count是特定日期和id的行数。 (例如p1的15-06-05计数为2)

+------------+--------------+------+-----+
| id         | date         | time | max |
+------------+--------------+------+-----+
| p1         | 15-06-06     | 8.00 | 20  |
| p1         | 15-06-07     | 8.00 | 20  |
| p2         | 15-06-07     | 9.00 | 10  |
| p3         | 15-06-08     | 8.00 | 20  | 
+------------+--------------+------+-----+

可以使用MySQL查询生成第三个表

我尝试了这个SELECT COUNT(booking.date)作为' count',setup.time,booking.date,setup.max FROM预订LEFT JOIN设置在booking.date = setup.date和预订。 id = setup.id和booking.id =' p1' GROUP BY booking.date ORDER BY booking.date ASC"

1 个答案:

答案 0 :(得分:0)

这样的东西,但我现在无法检查。 full join中没有MySql的痛苦:

SELECT COALESCE(id1, id2), COALESCE(date1, date2), COUNT(*), MAX(time), MAX(max)
FROM
    (SELECT b.id as id1, s.id as id2, b.date as date1, s.date as date2, s.time, s.max FROM booking b
     LEFT JOIN setup s on b.id = s.id and b.date = s.date
     WHERE b.id = 'p1'
     UNION
     SELECT b.id as id1, s.id as id2, b.date as date1, s.date as date2, s.time, s.max FROM booking b
     RIGHT JOIN setup s on b.id = s.id and b.date = s.date
     WHERE s.id = 'p1') t
GROUP BY COALESCE(id1, id2), COALESCE(date1, date2)