简体   繁体   中英

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). 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
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM