I'm creating a view that is using data that comes from the same table twice. As a result, same column names appear twice.
Thus, i need to give aliases to these columns. If i were to do it, i'd write it as:
SELECT u.* as 'one_*', u2.* as 'two_*'
FROM users u
LEFT JOIN relationships r ON u.id=r.id_one
LEFT JOIN users u2 ON r.id_two=u2.id
But that doesn't work. Thanks for your help!
EDIT:
Here's the data i'm actually getting:
| id | name | id | name |
1 john 2 alex
Here's the data i'd like to get (while still using a SELECT u.*, u2.*):
| id | name | brother_id | brother_name |
1 john 2 alex
You can't use * with an alias. Aliases can be used for individual columns.
You'll have to alias each column instead..
So unfortunately, if you have a lot of columns, you'll need to go:
SELECT u.col1 AS u_col1
, u.col2 AS u_col2
, u.col3 AS u_col3
-- etc
, u2.col1 AS u2_col1
, u2.col2 AS u2_col2
, u2.col3 AS u2_col3
-- etc
FROM table1 AS u
-- INNER JOIN / LEFT OR RIGHT OUTER JOIN / ,
table2 AS u2
Try using a UNION query:
e.g.
select a.typeid, a.typename from MYTABLE a where a.typeid=3 UNION select a.typeid, a.typename from MYTABLE a where a.typeid=4
Can you not just use SELECT * and then in your code refer to u.field1 and u2.field2?
I know this is an old question but I recently had the problem and came up with a solution.
First query the table and get the names of the columns
ex.
"SHOW COLUMNS FROM $table_name"
then use a loop to concat a prefix to the column name
ex
foreach ($all_columns as $the_column){
$alias_select .= ', '.$table_name.'.'.$the_column['Field'].' alias_'.$the_column['Field'];
}
then just put this string into your query and you will get another set of values all with the prefix_column_name.
SELECT alias.* does certainly work in mysql >= 5.6
Related
I have one table with user and their posts. It looks like "user_id | post_id | post_status".
Now I have a list of userid (ex, 100 users) and I want to know how many of them has at least one post that gets deleted (ex, post_status 3).
Here is my sample search:
select count(distinct user_id)
from post_table
where user_id in ( {my set} )
and post_status=3
It runs super slow since it iterates the entire table. Is there a way to speed up the query?
Use something like
SELECT COUNT(*)
FROM
-- the list of userid as a rowset
( SELECT 123 AS user_id UNION ALL
SELECT 456 UNION ALL
-- ...
SELECT 789
) user_id_list
WHERE EXISTS ( SELECT NULL
FROM post_table
WHERE post_table.user_id = user_id_list.user_id
AND post_table.post_status = 3 )
If your MySQL version is 8.0.4 or above then you may provide the users list as CSV/JSON and parse it using JSON_TABLE (the query text will be more compact).
INDEX(post_status, user_id)
may help speed up your query, especially if very few rows have status=3.
This could also speed up Akina's solution.
I have 3 tables that I am using and need to make a query to return data from one table based on the value of a single column in the second table.
tbl_user
ID
login
pass
active
mscID
tbl_master
ID
name
training_date
MSCUnit
Active
tbl_msc
mscID
mscName
my current SQL statement:
SELECT
tbl_master.ID,
tbl_master.name,
tbl_master.training_date,
tbl_master.MSCUnit,
tbl_master.active,
tbl_user.mscID
FROM
tbl_master,
tbl_user
WHERE
tbl_master.active = 1 AND tbl_master.MSCUnit = tbl_user.mscID
The values stored in tbl_msc.mscID is a varchar(11) and it contains a string similar to A00 or A19. This is also the Primary key in the table.
The values stored in tbl_user.mscID matches that of tbl_msc.mscID. The values stored in tbl_master.UnitMSC also matches that of tbl_msc.mscID.
My goal is to return all records from tbl_master where the currently logged in user has the same mscID. The problem I am having is the statement returns all records in tbl_master.
I have tried several different join statements and for some reason, I cannot get this to filter correctly.
I am missing something. Any assistance in the SQL statement would be appreciated.
Thanks,
Will
You should be writing this using joins. I don't know how you know who the current user is, but the idea is to join the three tables together:
SELECT m.ID, m.name, m.training_date, m.MSCUnit, m.active,
u.mscID
FROM tbl_master m JOIN
tbl_user u
ON m.MSCUnit = u.mscID JOIN
tbl_msc msc
ON msc.mscID = u.msc_ID
WHERE m.active = 1 AND msc.mscName = ?;
Notice the use of proper, explicit, standard JOIN syntax and table aliases.
Select a.*, b.userid from
table_master a, table_user b where
a.mscunit in (select mscid from
table_user where active=1)
This should point you in the right direction.
I have a table with the following syntax:
| ID | institution_course1_id | institution_course2_id |
where application1_id and application2_id references to the same table. I need to get the values of both (so in other words I want to retrieve the name of each application)
I tried to join the tables but I am still only receiving 1 name in my results. Here is my SQL I use:
SELECT * FROM `client_applications`
LEFT JOIN `institution_courses` `name1`
ON `client_applications`.`institution_course1_id`=`name1`.`id`
LEFT JOIN `institution_courses` `name2`
ON `client_applications`.`institution_course2_id`=`name2`.`id`
WHERE `client_applications`.`client_id`=?
Is there a way for me to return in my results all rows from client_applications and then have 2 seperate added keys as "name1" and "name2" based on the above?
I am guessing that your problem is the application reading the results. Try putting in different aliases ("column names") for the two names:
SELECT ca.*, name1.name as name1, name2.name as name2
FROM `client_applications` ca LEFT JOIN
`institution_courses` `name1`
ON ca.`institution_course1_id` = `name1`.`id` LEFT JOIN
`institution_courses` `name2`
ON ca.`institution_course2_id` = `name2`.`id`
WHERE ca.`client_id` = ?;
Otherwise your query looks fine (although I added an alias for the first table as well).
try below:
SELECT ca.*, (select name1.name from name1 where ca.`institution_course1_id` = `name1`.`id`) as name1,(select name1.name from name1 where ca.`institution_course2_id` = `name1`.`id`) as name2
FROM `client_applications` ca
WHERE ca.`client_id` = ?;
I have a list of ids, and I want to query a mysql table for ids not present in the table.
e.g.
list_of_ids = [1,2,4]
mysql table
id
1
3
5
6
..
Query should return [2,4] because those are the ids not in the table
since we cant view ur code i can only work on asumption
Try this anyway
SELECT id FROM list_of_ids
WHERE id NOT IN (SELECT id
FROM table)
I hope this helps
There is a horrible text-based hack:
SELECT
substr(result,2,length(result)-2) AS notmatched
FROM (
SELECT
#set:=replace(#set,concat(',',id,','),',') AS result
FROM (
select #set:=concat(',',
'1,2,4' -- your list here
,',')
) AS setinit,
tablename --Your tablename here
) AS innerview
ORDER BY LENGTH(result)
LIMIT 1;
If you represent your ids as a derived table, then you can do this directly in SQL:
select list.val
from (select 1 as val union all
select 2 union all
select 4
) list left outer join
t
on t.id = list.val
where t.id is null;
SQL doesn't really have a "list" type, so your question is ambiguous. If you mean a comma separated string, then a text hack might work. If you mean a table, then something like this might work. If you are constructing the SQL statement, I would advise you to go down this route, because it should be more efficient.
This has got to be a simple question, just brain-dumbing right now...
I've got one table, called 'foo'. It's got two columns, 'id' and 'username'.
The id is unique, but some of the usernames reference the same user; just one has a prefix on the username of 'xx_'.
ex:
ID USERNAME
1 bob
2 sam
3 xx_bob
How can I figure out which of the users have a counterpart with the 'xx_' prefix? And then which ones do not?
select * from foo where username
IN (select replace(username, 'xx_', '') from foo where username like 'xx_%')
What this does is compares the entire table against a sub list which is generated by the sub-query after the IN verb.
To do the opposite you can simply use a NOT IN in place of the IN.
NOTE: This is a t-sql (MS SQL 2005) query, should be similar in MySQL
This will give you the id's of both rows:
select * from foo a1 join foo a2 on (a2.username=concat('xx_',a1.username));
If you want every rows that isn't a duplicate, with the duplicate_id:
SELECT foo.*, f2.id AS duplicate_id FORM foo
LEFT OUTER JOIN foo AS f2 ON ( f2.username = concat( 'xx_', foo.username ) )
WHERE foo.id NOT LIKE 'xx_%'