如何用 select 连接 2 个表并在单个查询中计数
How to join 2 tables with select and count in a single query
我是 Whosebug 的新手,对于这里的大多数人,我可能有一个非常简单的问题:)
对 php 和 mysql 了解不多,这就是我决定寻求帮助的原因。
我有 2 个 table:
第一个 table 使用 id 和 name 调用了 tags。
第二个 table 名为 products,我的重点是 description。
这就是我想要完成的:
Select name 来自 tags table,将其传递到 products table, 找出在 products table description[= 里面有多少产品包含 name 48=] 并得到 count。也只显示计数大于 0 的结果,隐藏值为 0 的 name。并按计数从高到低对结果进行排序。
最终结果示例:
name1 (15), name2 (9), name3 (5) 等等
name4 (0) - 隐藏
希望有人能理解我在这里写的我的天啊:)
我正在编辑现成的脚本并且对 php 和 mysql 知之甚少所以不要对我太苛刻 :)
您可以加入和聚合:
select t.name, count(*) cnt
from tags t
inner join products p on p.description like concat('%', p.name, '%')
group by t.id, t.name
我在 group by
子句中添加了标签的 id
,以防有重复的标签 name
s - 如果没有,这也不会造成伤害.
尝试 1 - 这会找到“%”tags.name“%”
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
GROUP BY tags.name
ORDER BY COUNT(name) DESC
尝试 2 - 添加 WHERE tags.id <> 0
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
WHERE tags.id <> 0
GROUP BY tags.name
ORDER BY COUNT(name) DESC
尝试 3 - 如果您需要多个隐藏标签,您可以在 'hide' 的标签中添加一列。
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
WHERE tags.hide = 0
GROUP BY tags.name
ORDER BY COUNT(name) DESC
我是 Whosebug 的新手,对于这里的大多数人,我可能有一个非常简单的问题:)
对 php 和 mysql 了解不多,这就是我决定寻求帮助的原因。
我有 2 个 table:
第一个 table 使用 id 和 name 调用了 tags。
第二个 table 名为 products,我的重点是 description。
这就是我想要完成的:
Select name 来自 tags table,将其传递到 products table, 找出在 products table description[= 里面有多少产品包含 name 48=] 并得到 count。也只显示计数大于 0 的结果,隐藏值为 0 的 name。并按计数从高到低对结果进行排序。
最终结果示例:
name1 (15), name2 (9), name3 (5) 等等
name4 (0) - 隐藏
希望有人能理解我在这里写的我的天啊:)
我正在编辑现成的脚本并且对 php 和 mysql 知之甚少所以不要对我太苛刻 :)
您可以加入和聚合:
select t.name, count(*) cnt
from tags t
inner join products p on p.description like concat('%', p.name, '%')
group by t.id, t.name
我在 group by
子句中添加了标签的 id
,以防有重复的标签 name
s - 如果没有,这也不会造成伤害.
尝试 1 - 这会找到“%”tags.name“%”
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
GROUP BY tags.name
ORDER BY COUNT(name) DESC
尝试 2 - 添加 WHERE tags.id <> 0
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
WHERE tags.id <> 0
GROUP BY tags.name
ORDER BY COUNT(name) DESC
尝试 3 - 如果您需要多个隐藏标签,您可以在 'hide' 的标签中添加一列。
SELECT count(name) as c, MIN(name) as n FROM tags
LEFT JOIN products
ON products.description LIKE CONCAT( '%', tags.name, '%' )
WHERE tags.hide = 0
GROUP BY tags.name
ORDER BY COUNT(name) DESC