我有3个表:制造商,产品和客户 我有一个查询,让我所有的制造商与他们的产品和他们的客户。我用两个LEFT JOINS做到了这一点。
对于10个制造商而言,结果超过500行,因为对于产品和客户表中的每个条目,它们是结果中具有制造商ID的行。
我想创建一个查询:向我的制造商提供他们的产品和他们的客户,但不是所有的制造商,只有10或20或有限的数量。
我该怎么做? 我在想这个......
SELECT *
FROM manufacturer as m
LEFT JOIN product as p ON ( m.mn_id = p.man_mn_id )
LEFT JOIN client as c ON ( m.mn_id = c.man_mn_id )
WHERE m.mn_id IN ( SELECT mn_id
FROM manufacturer
WHERE mn_id >= ( SELECT FLOOR( MAX(mn_id) * RAND() )
FROM manufacturer
)
ORDER BY mn_id
LIMIT 10
)
或者他们是更好的方式?
答案 0 :(得分:1)
您可以通过限制制造商来尝试这一点,它将获得10个制造商,并将这些制造商加入他们的产品和客户
SELECT
*
FROM
(SELECT
*
FROM
manufacturer
ORDER BY id DESC
LIMIT 10) AS m /* you can change limit to 20 or something you want */
LEFT JOIN product AS p
ON (m.mn_id = p.man_mn_id)
LEFT JOIN CLIENT AS c
ON (m.mn_id = c.man_mn_id)
答案 1 :(得分:1)
我认为您可以将查询简化为类似的内容,保留查询中的“随机”功能:
SELECT *
FROM (SELECT * FROM manufacturer ORDER BY RAND() LIMIT 10) as m
LEFT JOIN product as p ON (m.mn_id = p.man_mn_id)
LEFT JOIN client as c ON (m.mn_id = c.man_mn_id)
ORDER BY mn_id