User11
User11

Reputation: 3

How can i union sql query

I have to queries:

SELECT * FROM `posts` WHERE `id` = '{$id}'
SELECT * FROM `post_votes` WHERE `post` = '{$id}' AND `user` = '{$user}'

Can I join them together into one query (some column names are similar) and get assoc array using mysqli_fetch_assoc?

Thank you.

Upvotes: 0

Views: 841

Answers (1)

Sofien
Sofien

Reputation: 1670

I'm not sure to understand exactly your tables structures but I think what you are looking for is UNION ALL
So your query might look like:

SELECT col_1, col_2 FROM `posts` WHERE `id` = '{$id}'*
UNION ALL
SELECT col_1, col_2 FROM `post_votes` WHERE `post` = '{$id}' AND `user` = '{$user}'

If posts and post_votes don't have same column names you will have to use aliases. See https://www.techonthenet.com/postgresql/union_all.php fore more details

Upvotes: 2

Related Questions