Mysql 带左联接子查询的sql
所以我想问一下,是否可以将这两个查询合并起来。我有三张桌子: 养蜂场可以有多个蜂巢 蜂巢一次只能在一个养蜂场 movedate蜂房和蜂房之间的m:n表,蜂房位于蜂房上时带有日期字段 我的第一个是,它只是得到了用户的蜂巢:Mysql 带左联接子查询的sql,mysql,join,Mysql,Join,所以我想问一下,是否可以将这两个查询合并起来。我有三张桌子: 养蜂场可以有多个蜂巢 蜂巢一次只能在一个养蜂场 movedate蜂房和蜂房之间的m:n表,蜂房位于蜂房上时带有日期字段 我的第一个是,它只是得到了用户的蜂巢: SELECT apiary_id as id, name FROM apiary WHERE modus = '1' //if apiary is aktive
SELECT apiary_id as id, name
FROM
apiary
WHERE
modus = '1' //if apiary is aktive
AND
user_id = ?
第二个则计算当前每个蜂房上有多少个蜂箱:
SELECT
COUNT(*) AS count
FROM
movedate
LEFT JOIN //get rows with the same apiary_id
apiary
ON
movedate.apiary_id = apiary.apiary_id
LEFT JOIN //get rows with the same hive_id
hive
ON
movedate.hive_id = hive.hive_id
LEFT OUTER JOIN //outer join to check for the joungest date
movedate as movedate2
ON movedate.hive_id = movedate2.hive_id
AND (movedate.date < movedate2.date
OR (movedate.date = movedate2.date AND movedate.id < movedate2.id))
WHERE
hive.modus = '1' //check if hive is active
AND
apiary.apiary_id = $ap_id //get apiary id (at the moment to this query for each apiary)
AND
movedate2.hive_id IS NULL (dont get the old entries)
我试图简单地将整个第二个SQL查询作为SELECT中的子查询移动到第一个SQL查询中,但似乎无法在SELECT子查询中执行左连接?如果要使用特殊命令,我将使用PDO
我很乐意得到任何提示
干杯
汉内斯我想你只需要一组人:
太棒了,我的想法太复杂了非常感谢你!
SELECT apiary.apiary_id, COUNT(*) AS count
FROM movedate LEFT JOIN //get rows with the same apiary_id
apiary
ON movedate.apiary_id = apiary.apiary_id LEFT JOIN //get rows with the same hive_id
hive
ON movedate.hive_id = hive.hive_id LEFT OUTER JOIN //outer join to check for the joungest date
movedate as movedate2
ON movedate.hive_id = movedate2.hive_id AND
(movedate.date < movedate2.date OR
(movedate.date = movedate2.date AND movedate.id < movedate2.id)
)
WHERE hive.modus = '1' AND //check if hive is active
movedate2.hive_id IS NULL (dont get the old entries)
GROUP BY apiary.apiary_id;