[英]I want to use two queries into one using a column from first query in the second one in MySQL
I have these two queries:我有这两个查询:
The first one:第一个:
SELECT * FROM item, user WHERE item_def = '289'
AND item_quality = '6' AND user.steam_64 = item.steam_64
The second one:第二个:
select count(item_id) from item where steam_64 = '".$steam_id64."'"
So basically, my first query is returning the users for the matching item (in this case item = 289).所以基本上,我的第一个查询是返回匹配项的用户(在本例中为 item = 289)。 My second query is just looking how many items in total has every user returned in the first query.我的第二个查询只是查看每个用户在第一个查询中返回的项目总数。
I would like to have that count in the first query.我想在第一个查询中有这个计数。
You can just copy the second query and paste it into the select list of the first.您可以复制第二个查询并将其粘贴到第一个查询的 select 列表中。
SELECT
item.*,
user.*,
(select count(item_id) from item where steam_64 = '$steamid64') AS `count`
FROM
item
INNER JOIN
user
ON
item.steam_64 = user.steam_64
WHERE
item.item_quality = 6
AND
item.item_def = 289
I feel like a mother saying to her child eat your vegetables , but... write out your joins and don't quote your numbers .我感觉就像一位母亲对她的孩子说吃你的蔬菜,但是……写下你的加入,不要引用你的数字。
I believe this is simply a matter of adding a GROUP BY clause since all you're interested from the second table is just the count.我相信这只是添加一个 GROUP BY 子句的问题,因为您对第二个表感兴趣的只是计数。
Putting an additional SELECT statement in the main SELECT statement will cause an additional SELECT query to be done for every row returned -- which could lengthen query time dramatically.在主 SELECT 语句中添加额外的 SELECT 语句将导致对返回的每一行执行额外的 SELECT 查询——这可能会显着延长查询时间。
Here's how I'd to this:这是我的做法:
SELECT
count (*) as count_of_items,
user.*
FROM
user join item on item.steam_64 = user.steam_64
WHERE item.item_quality = 6 AND item.item_def = 289
GROUP BY user.steam_64
The GROUP BY clause just has to be done based on some column that's the same for every joined row. GROUP BY 子句只需要基于对于每个连接行都相同的列来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.