1

I got two sql statements:

SELECT username AS userA FROM WHERE username='abc'
SELECT username AS userB FROM WHERE username='abcd' AND password='abcd'

I want to output the result as below:

userA  |  userB
----------------
abc    |  abcd

How to combine two SQL statements?

3
  • I don't think you can join them like that. The closest I know of is a union, which will select them as two rows instead of two columns. Commented Feb 2, 2016 at 1:49
  • Why are you selecting the username when you already know what it is? (The value is in the where clause.) Commented Feb 2, 2016 at 1:52
  • Can you provide us with some table structure? The easiest way to handle this would be to join the two tables together. Commented Feb 2, 2016 at 1:52

4 Answers 4

1
SELECT tableA.username as userA
    tableB.username as userB
FROM tableA
CROSS JOIN table B
WHERE tableA.username='abc'
    AND tableB.username='abcd'
    AND tableB.password='abcd';

CROSS JOIN! :P CARTESIAN PRODUCT!

Sign up to request clarification or add additional context in comments.

Comments

1

You can combine tables and fields with the syntax:

SELECT tableA.username as userA
    tableB.username as userB
FROM tableA
JOIN table B
WHERE tableA.username='abc'
    AND tableB.username='abcd'
    AND tableB.password='abcd';

Unless there's some kind of relation between the tables, you'll be getting the cross product times rows, so it might be an NxM result which is just useless.

Comments

1

I haven't try it but here something you can try:

SELECT 
  (SELECT username AS userA FROM WHERE username='abc' LIMIT 1) AS 'userA',
  (SELECT username AS userB FROM WHERE username='abcd' AND password='abcd' LIMIT 1) AS 'userB';

Comments

1

try this:

select t1.userA,t2.userB  
 from
      (SELECT username AS userA FROM WHERE username='abc')t1
 join (SELECT username AS userB FROM WHERE username='abcd' AND password='abcd')t2
 where 1=1

where 1=1 will combine any 2 queries without condition but it's meaningless. Although it match what you asked i don't suggest people use it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.