我有一张这样的表
id userid game date_t hdigit inside outside
1 user101 xy 02-09-2017 1 10
2 user101 xy 02-09-2017 1 40
3 user101 xx 02-09-2017 2 40
4 user101 xx 02-09-2017 3 90
我想要显示数据,如
id userid game date_t hdigit inside outside
1 user101 xy 02-09-2017 1 10 40
3 user101 xx 02-09-2017 2 40
4 user101 xx 02-09-2017 3 90
我试过这个
SELECT h.userid,h.game,h.date_t,h.hdigit,h.inside,htwo.outside
FROM `hadap_game` AS h JOIN hadap_game AS htwo WHERE h.userid=:user
AND htwo.userid=:uer AND h.hdigit=htwo.hdigit AND h.game=htwo.game
AND h.inside IS NOT NULL AND htwo.outside IS NOT NULL
它打印上面的东西,但我想要打印具有空值的行
答案 0 :(得分:1)
我认为你可以简单地使用GROUP BY
吗?
SELECT
h.userid,
h.game,
h.date_t,
h.hdigit,
MAX(IFNULL(h.inside, htwo.inside)) AS inside,
MAX(IFNULL(h.outside, htwo.outside)) AS outside
FROM
hadap_game AS h
LEFT JOIN hadap_game AS htwo ON htwo.userid = h.userid AND htwo.hdigit = h.hdigit AND htwo.game = h.game AND htwo.id <> h.id
WHERE
h.userid = :user
GROUP BY
h.userid,
h.game,
h.date_t,
h.hdigit;
这会做一些你可能不需要/想要的其他事情,但它与原始查询基本相同,除了它在每个唯一引用没有两行时起作用。
答案 1 :(得分:0)
假设只有1或2行(所以不是3个或更多匹配的行): -
SELECT h.userid,
h.game,
h.date_t,
h.hdigit,
COALESCE(h.inside,h2.inside) AS inside,
COALESCE(h.outside,h2.outside) AS outside
FROM `hadap_game` AS h
LEFT OUTER JOIN hadap_game AS h2
ON h.hdigit=h2.hdigit
AND h.game=h2.game
WHERE h.userid=:user
AND h2.userid=:uer
UNION
SELECT h2.userid,
h2.game,
h2.date_t,
h2.hdigit,
COALESCE(h.inside,h2.inside) AS inside,
COALESCE(h.outside,h2.outside) AS outside
FROM `hadap_game` AS h2
LEFT OUTER JOIN hadap_game AS h
ON h.hdigit=h2.hdigit
AND h.game=h2.game
WHERE h.userid=:user2
AND h2.userid=:uer2