Add dynamic number of variables to WHERE clause in mysql - php

I have the following mySQL query:
SELECT act_id, vote_date, vote_score, 'vote' AS type
FROM votes
WHERE user_voter = '1'
I want to be able to add and user_voter to the WHERE clause based on the result of another mySQL query. For example,
SELECT user_2
FROM friends
WHERE user_1 = '1'
This will output a dynamic amount of results based on the number of matches.
So, if the second query outputs:
3
4
11
32
Then I want the first query to be:
SELECT act_id, vote_date, vote_score, 'vote' AS type
FROM votes
WHERE user_voter = '1' AND user_voter = '3' AND user_voter = '4' AND user_voter = '11' AND user_voter = '32'
Hope this makes sense!
Since I am using PHP I was thinking I might have to create a while loop and have it output the results as "user_voter = '".$user2."' "; and then append it to the SELECT query before running.

You can do a subquery inside an IN()
SELECT act_id, vote_date, vote_score, 'vote' AS type
FROM votes
WHERE user_voter IN (
SELECT user_2
FROM friends
WHERE user_1 = '1'
)

Related

Selecting different rows with same id but different values

I have a table above, I want to get the record_id(3 in this case) having meta_name=discount_percent and meta_value=56 combined with another condition meta_name=discount_multiplier and meta_value=30. I tried using HAVING clause with GROUP BY but it didn't work.
Would appreciate if someone can help.
I believe you want to get the records with your two conditions group them by the ID and check if the count of rows in the group is 2, so that both conditions applied to that ID (assuming that the pair of record_id and meta_name is unique).
SELECT record_id
FROM elbat
WHERE meta_name = 'discount_percent'
AND meta_value = '56'
OR meta_name = 'discount_multiplier'
AND meta_value = '30'
GROUP BY record_id
HAVING count(*) = 2;

IF in WHERE mysql query

I have this table.
In MySql I want select this user IF key column do not have custom row AND IF key column have custom row -> value column = yes.
This is my query, but it do not work:
where `value` = if(`key` = 'custom', 'yes', '')
you can use the following statement which select any row has key not equal 'custom' or equal 'custom' and value equal 'yes'
Select * from tableName where `key`<> 'custom' or (`key` = 'custom' and `value` = 'yes')
The specification for the query isn't clear, in that it's open to several different interpretations.
I'm thinking the question is about how to return a particular result, not really about using an IF() function in the WHERE clause. (None of the SQL below uses an IF() function in a WHERE clause.)
Here's one possible interpretation of the specification:
By "select this user", we'll take that to mean we want to return a single copy of the user_id column.
By "IF key column do not have custom row", we'll take that to mean that there does not exist such a row for this user_id, then return this user_id. If such a row does exist, then do not return the user.
By "AND IF key column have custom row -> value column = yes.", we'll take that to mean to return this user_id if there is a row for this user_id that matches the condition.
Based on that interpretation, here's an approach to satisfying the specification using conditional aggregation:
SELECT t.user_id
FROM this_table t
GROUP
BY t.user_id
HAVING SUM(1) = SUM(IF(t.key='custom',IF(t.value='yes',1,0),1))
The expression inside the SUM() aggregate gets evaluated for each row. That expression is designed to return either a 1 or a 0, depending on whether the row matches the specified conditions. The SUM() aggregate totals up those 1s and 0s. And then we compare the result to the total number of rows. That tells us if a "matching" row exists or not.
The counts are by user_id, as identified in the GROUP BY clause.
The MySQL IF() function can be replace with a more portable ANSI CASE expression
HAVING SUM(1) = SUM(CASE
WHEN t.key = 'custom'
THEN CASE
WHEN t.value = 'yes'
THEN 1
ELSE 0
END
ELSE 1
END
)
If the intent is to return all of the detail rows for a user, but excluding all user_id that meet the specification, we could use an EXISTS correlated subquery:
SELECT t.user_id
, t.key
, t.value
FROM this_table t
WHERE NOT EXISTS ( SELECT 1
FROM this_table r
WHERE r.user_id = t.user_id
AND r.key = 'custom'
)
OR EXISTS ( SELECT 1
FROM this_table q
WHERE q.user_id = t.user_id
AND q.key = 'custom'
AND q.value = 'yes'
)

Mysql : last five records if having same value

I searched a lot and tried many queries but not getting satisfied answer. So like to ask.
I am looking for last 5 records from mysql table if having same value otherwise not.
Something like if col_n is having same value x from last 5 records then count otherwise not. But I am not able to figure out how to write query for this ?
SELECT count(col_n)
from track if(last five col_n = 'ok')
WHERE col_a = 'value1' AND col_b = 'value2'
enter mysql table records
Please try this:
SELECT p.*
FROM
( SELECT *
FROM demo ORDER by id DESC
LIMIT 5
) AS p
JOIN
( SELECT COUNT(*) AS cnt
FROM
( SELECT 1
FROM demo
LIMIT 5
) AS tmp
) AS c
ON c.cnt = 5 WHERE p.name='x'

How Can Identify Table in Mysql Union All

I Have Query As the following
SELECT * FROM (
(
SELECT * FROM comments
WHERE user_id = '66' AND product_id = '3'
AND status = 1
)
UNION ALL
(
SELECT * FROM comments_reply
WHERE user_id = '66' AND product_id = '3'
AND status = 1 )
) results
ORDER BY datetime DESC
Which Gets Data from two tabel and shows it in order to datetime.now frontside i am showing this data. but now i wants to know that which data is came from which table.
because I am calling a modal to show a comment in modal by this
<span class="showcomment text-danger"
data-cid = <?=$row[0]?>>view Comment</span>
But $row[0] Gives me an id But How can i identify that this id is came from which Table ?
I would rewrite your query as with tablename that you want
SELECT 'comments' as table_name, col1, col2,... coln FROM comments c
WHERE user_id = '66' AND product_id = '3'
AND status = 1 UNION ALL
SELECT 'comments_reply' as table_name, col1, col2,... coln FROM comments_reply cr
WHERE user_id = '66' AND product_id = '3'
ORDER BY col DESC
And, i suspect if you have user_id, product_id has numeric type then you should use only values without single quote.
where user_id = 66 AND product_id = 3
You can add a column to each of your two tables and populate it with a custom string. For example, the first sub query would start like the following with the new column “table_name”... select *, ‘comments’ table_name from comments...
SELECT * FROM (
(
SELECT "comments" as tablename,* FROM comments
WHERE user_id = '66' AND product_id = '3'
AND status = 1
)
UNION ALL
(
SELECT "comments_reply" as tablename,* FROM comments_reply
WHERE user_id = '66' AND product_id = '3'
AND status = 1 )
) results
ORDER BY datetime DESC

Getting counts of grouped fields, but also need field names with zero counts

you've probably seen it before. I'm trying to get the counts of how many sms messages belong in folders, but I want to still have the field named show up that don't contain any smses.
For Example:
TABLE: inbox_compiled
message_text(text)
id_folder(int)
TABLE: user_folders
id_folder(int)
name(text)
This is the mysql statement I use:
SELECT
user_folders.id_folder, name, COUNT(*) as msg_count
FROM inbox_compiled, user_folders
WHERE
inbox_compiled.id_folder = user_folders.id_folder
GROUP BY name ORDER BY msg_count DESC
My results are this:
id_folder,name,msg_count
'1', 'inbox', '25'
'2', 'outbox', '1'
What I should (or would like to) get is this):
id_folder,name,msg_count
'1', 'inbox', '25'
'2', 'outbox', '1'
'3', 'spam', '0'
'4', 'personal', '0'
'5', 'junk', '0'
(I know the table fields aren't the best - it's what I'm working with right now)
Thanks in advance.
Something like this.
SELECT
user_folders.id_folder, name, COUNT(inbox_compiled.id_folder) as msg_count
FROM user_folders left join inbox_compiled on (inbox_compiled.id_folder = user_folders.id_folder)
GROUP BY name ORDER BY msg_count DESC;
Use outer join and also do not use count(*) but just count the message ids, e.g.
select f.id_folder, f.name, i.*, count(i.id) as msg_count from user_folders as f left join inbox_compiled as i on i.id_folder = f.id_folder group by f.name;

Categories