I currently have two tables that have the same column names;
APPLICATION_Reference.firstName, APPLICATION_Reference.lastName
APPLICATION_Recommendation.firstName, APPLICATION_Recommendation.lastName
$all_references = mysqli_query($con, "SELECT *
FROM APPLICATION_Reference
INNER JOIN APPLICATION_Recommendation
ON APPLICATION_Reference.referenceId = APPLICATION_Recommendation.referenceId
INNER JOIN Applicant ON APPLICATION_Reference.firstName = Applicant.givenName
ORDER BY APPLICATION_Reference.referenceId ASC");
And then I have an echo statement where I echo out my data: $applicant_reference['firstName']
My question is: How do I differentiate between my different tables when echoing out the column names?
Use table aliases and column aliases.
In your query you can alias a whole table to make things more readable, e.g.
APPLICATION_Reference ref
Your query then becomes
SELECT *
FROM APPLICATION_Reference ref
INNER JOIN APPLICATION_Recommendation rec ref.referenceId = rec.referenceId
INNER JOIN Applicant app ON ref.firstName = app.givenName
ORDER BY ref.referenceId ASC
Instead of then using SELECT *, list the fields you are interested in and rename them to something that makes sense in your result set, e.g.
SELECT ref.firstName reference_first_name,
rec.firstname recommendation_first_name,
...
You can then access the new column names in your PHP code. You certainly don't have to use such long references (e.g. reference_first_name) - those are just examples.
you could use
SELECT *, table1.field AS field1, table2.field AS field2 ...
and then reference the fields as field1 and field2 in your output
You can use aliases
SELECT
APPLICATION_Recommendation.lastName as APPLICATION_Recommendation_lastName,
Applicant .lastName as Applicant _lastName
...
FROM APPLICATION_Reference
INNER JOIN APPLICATION_Recommendation ON APPLICATION_Reference.referenceId = APPLICATION_Recommendation.referenceId
INNER JOIN Applicant ON APPLICATION_Reference.firstName = Applicant.givenName
ORDER BY APPLICATION_Reference.referenceId ASC
Related
Please help me to write correct query for a few tables. I need to replace all id here from another table
api json
I am trying to make query like this
SELECT incident.`number`, `user`.first_name, (SELECT `user`.first_name from ITSM.`user` JOIN incident on `user`.sys_id = incident.id_created_by) as createdby
from ITSM.incident
JOIN ITSM.`user` on incident.id_caller = `user`.sys_id
;*
but it doesn#t work, I got an error: Subquery returns more than 1 row
How can i make a right query?
This one doesn't work also, same error:
SELECT incident.`number`, (SELECT user.first_name from ITSM.`user`, ITSM.incident WHERE user.sys_id = incident.id_created_by) as createdby
from ITSM.incident
JOIN ITSM.`user` on incident.id_caller = user.sys_id*
;
and this is my
DB id for user who created
You don't need a subquery. Just refer to the source table of each column in the select clause, here if you need 2 joins to the same table give these an alias and refer to the columns using that alias.
SELECT incident.`number`
, caller.first_name as caller_name
, creator.first_name AS createdby
FROM ITSM.incident
JOIN ITSM.`user` AS caller ON incident.id_caller = caller.sys_id
JOIN ITSM.`user` AS creator ON incident.id_created_by = creator.sys_id
Nb. I'm assuming your join logic is correct
I'm trying to create an SQL query which filters information by customerID in one table and then combine that with information in another table. I have this query which filters by customerID
$query = mysqli_query($connection, "
SELECT *
FROM booked_activities
WHERE customerID LIKE $_SESSION[customerID]
");
/* INNER JOIN activities ON booked_activities.activityID = activities.activityID);*/
The second part I commented out is where I tried to combine the first half of the query with another table.
The activityID is a common ID in tables: booked_activites and activities.
Right now I can output the first query as activityID but I need to use the activityID to output the activityName from the activities table.
have you tried
$query = mysqli_query($connection, "SELECT *,ac.activityName FROM booked_activities INNER JOIN activities ac ON booked_activities.activityID = activities.activityID
WHERE customerID LIKE $_SESSION[customerID] );
also I would suggest using prepared statement for passing custometr id, instead of using sesstion variable directly in string.
SELECT * FROM booked_activities t1
join activities t2 on t2.activityID = t1.activityID
WHERE t1.customerID LIKE $_SESSION[customerID]
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.
I am running into some trouble with the following circumstances:
I have a query that creates two temp tables, and the following select to join them together--
SELECT * FROM result
INNER JOIN result2 ON result2.packetDetailsId = result.packetDetailsId
I am then trying to create another column from concatenating a few of the resulting fields and then use that to reference/query against another table. Is there a way to accomplish this in one query? Should I get away from the temp tables?
Thank you again in advance.
update: If I try to alias the combination of the two temp tables I get an error message stating [Err] 1060 - Duplicate column name 'packetDetailsId'
select * from (
SELECT * FROM result
INNER JOIN result2 ON result2.packetDetailsId = result.packetDetailsId) as myalias
Another Update: I almost have it working as one query but I get the result "(BLOB)" in the column I concoctenated:
select packet_details.packetDetailsId,products.productId,Credit,AccountNum,OrderStat, CONCAT(products.productId,Credit,'_',OrderStat) as consol from (
select packetDetailsId, GROUP_CONCAT(Credit) AS Credit, GROUP_CONCAT(AccountNum) AS AccountNum, GROUP_CONCAT(OrderStat) AS OrderStat FROM
( SELECT pd_extrafields.packetDetailsId,
CASE WHEN pd_extrafields.ex_title LIKE ('%Credit%')
THEN pd_extrafields.ex_value ELSE NULL END as Credit,
CASE WHEN pd_extrafields.ex_title LIKE ('%Account%')
THEN pd_extrafields.ex_value ELSE NULL END as AccountNum,
CASE WHEN pd_extrafields.ex_title LIKE ('%Existing%')
THEN pd_extrafields.ex_value ELSE NULL END as OrderStat
FROM pd_extrafields )AS TempTab GROUP BY packetDetailsId ) as alias2
INNER JOIN packet_details ON alias2.packetDetailsId = packet_details.packetDetailsId
INNER JOIN sales ON packet_details.packetDetailsId = sales.packetDetailsId
INNER JOIN sold_products ON sales.saleId = sold_products.saleId
INNER JOIN products ON sold_products.productId = products.productId
If I understand correctly, you already have the temporary tables created and you need to "concatenate" the results, using from ... inner join ...
The only possible restriction you may have is that you can only reference your temporary tables once in your from clause; besides that, there are no other restrictions (I frequently use temporary tables as intermediate steps in the creation of my final result).
Tips
Let's say your temp tables are temp_result1 and temp_result2. Both tables have a field packedDetailsId, on which the join will be performed. Remember to create the appropriate indexes on each table; at the very least you need to index packedDetailsId on both tables:
alter table temp_result1
add index PDI(packedDetailsId);
alter table temp_result2
add index PDI(packedDetailsId);
Now, just execute a query with the desired join and concatenation. If concat returns BLOB, then cast the result as char (of course, I'm assuming you need a text string):
select r1.*, r2.*, cast(concat(r1.field1, ',', r2.field2) as char) as data_concat
from temp_result1 as r1
inner join temp_result2 as r2 on r1.packedDetailsId = r2.packedDetailsId;
I see your problem is that GROUP_CONCAT is returning BLOB values... It's normal (MySQL doesn't know a priori how to return the values, so it returns binary data); just use the cast function.
Hope this helps you
so, if the result2 and result are both temp tables, you will have to include the # if local temp table and ## if global temp table
so your statements should be :
SELECT * FROM #result
INNER JOIN #result2 ON #result2.packetDetailsId = #result.packetDetailsId
My Bad. This is only applicable for MS SQL
I have an existing mysql query that I need to add to and I'm not sure how to go about it.
Here is my current sql query.
SELECT tbl_brokerage_names.brokerage_id, tbl_brokerage_names.short_name,
b.indication, b.max_indication
FROM tbl_brokerage_names
LEFT JOIN (
SELECT * FROM tbl_recommendation_brokerages
WHERE recommendation_id = {$_GET['id']}
) b ON (tbl_brokerage_names.brokerage_id = b.brokerage_id)
ORDER BY tbl_brokerage_names.short_name ASC
Here is the query that I need to work into the previous query.
SELECT * , COUNT( * )
FROM tbl_streetaccounts
JOIN tbl_brokerage_names
WHERE tbl_brokerage_names.brokerage_id = tbl_streetaccounts.brokerage_id
Basically I need to return a count, so I need to combine these two queries.
You should run these as two separate queries.
The COUNT(*) query will return a single row, so there's no way to "combine" it with the first query while preserving the multi-row result of the first query.
Also, when you SELECT *, COUNT(*) you will get columns from some arbitrary row.
By the way, you have a glaring SQL injection vulnerability. Don't interpolate $_GET parameters directly in your SQL query. Instead, coerce it to an integer:
<?php
$id = (int) $_GET['id'];
$sql = "SELECT ... WHERE recommendation_id = {$id}";
Like #Bill said, you cannot get the count in every row without really weird syntax, but you can get an overall count using GROUP BY ... WITH ROLLUP.
e.g.:
<?php
$id = mysql_real_escape_string($_GET['id']); //works with anything, not just numbers
$query = "
SELECT tbl_brokerage_names.brokerage_id
, tbl_brokerage_names.short_name
, b.indication
, b.max_indication
, count(*) as rowcount
FROM tbl_brokerage_names
LEFT JOIN (
SELECT * FROM tbl_recommendation_brokerages
WHERE recommendation_id = '$id' //The single quotes are essential for safety!
) b ON (tbl_brokerage_names.brokerage_id = b.brokerage_id)
GROUP BY tbl_brokerage_names.brokerage_id WITH ROLLUP
ORDER BY tbl_brokerage_names.short_name ASC
";
The GROUP BY .. WITH ROLLUP will add an extra line to the result with all NULL's for the non aggregated columns and a grand total count.
If you have any lines where rowcount > 0 then you need to add extra clauses from table b to the group by clause to prevent MySQL from hiding arbitrary rows.
Table tbl_brokerage_names is already fully defined because you are grouping by the primary key.