开发者

I want to use two queries into one using a column from first query in the second one in MySQL

开发者 https://www.devze.com 2023-03-28 11:03 出处:网络
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

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). My second query is just looking how many items in total has every user returned in the first query .

I would l开发者_运维技巧ike 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
  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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号