I had my query set up the other day as so
$query = "SELECT card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest order by card_id";
As you can see, I was selecting card_id,title,description,meta_description,seo_keywords from the table cards, and price was coming from cheapest_card. They both have the card_id in common (in both tables). However, I ran into a bit of an issue. When I run the query in navicat lite, I receive an error "card_id is ambiguous". Was I doing something wrong?
When 2 or more tables have a column that is named the same, you have to qualify the table you want the column to be from.
i.e.:
$query = "SELECT cards.card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest order by card_id";
Furthermore, do you really want to run the query this way, without a WHERE/JOIN-clause to define how to JOIN the two tables?
$query = "SELECT cards.card_id,title,description,meta_description,seo_keywords,price
FROM cards,card_cheapest WHERE cards.card_id = card_cheapest.card_id
ORDER BY card_id";
When you have the same column name in two tables you're selecting from, you have to prefix the part in the SELECT with one of the table names (it doesn't matter which if it's the same data)
such as SELECT cards.card_id, ...
EDIT: However, cularis's answer is much more explanatory than mine, and take note about joining the two card_id columns if you want to get correct results.
When you run queries that get information from multiple tables with shared field names you need to specify from which table you want to extract what field. You do this by specifying the table name before the field name.
In your case you have two options:
cards.card_id or card_cheapest.card_id.
Also I agree with #cularis, you are probably better of doing a join, but still you will need to specify which card_id you want to select: the one from cards or card_cheapest.
Related
I'm trying to create a mysql table from the inner join between two other tables. I'm dealing with a database someone creates which has the following tables:
sitematrix_sites
sitematrix_databases
They are related by another table (I don't know why don't use a foreign key) called sitematrix_sites_databases which has the following fields:
site_id and database_id.
That's how the two tables relate. Now I'm trying to remove that to make my life easier, so I have:
mysql> CREATE TABLE result AS(select * from sitematrix_databases INNER JOIN site
matrix_site_databases ON sitematrix_site_databases.database_id = sitematrix_data
bases.database_id);
ERROR 1060 (42S21): Duplicate column name 'database_id'
However, I'm getting that error. Does someone know how can I merge the two tables without repeating the database_id field?
Thanks
Remove the * in your SELECT statement and actually list out the columns you want in your new table. For columns that appear in both original tables, name the table as well (e.g. sitematrix_databases.database_id).
Don't use * instead name each column and use aliases. For instance instead of sitematrix_database.database_id you can have alternativeName. Also you can pick and choose which columns you want this way as well.
In SQL Server, you can use "select into". This might be equivalent syntax for mySql:
http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html
Unfortunately, it's a two commands (not just one):
http://www.tech-recipes.com/rx/1487/copy-an-existing-mysql-table-to-a-new-table/
CREATE TABLE recipes_new LIKE production.recipes; INSERT recipes_new SELECT * FROM production.recipes;
Instead of using SELECT * ... try SELECT database_id ...
MySQL does not like joining tables that have the same column name.
I am building a site and i need to retrieve some information. I have this query.
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 ";
I need to add this other code:
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])."'
but it's not working...
i need to compare let's say the id of another table with the id of the current table... How to do that?
Thanks in advance...
You should learn something about joining tables...
Do not know what the relation is between the two tables (simply said: what column from one table is pointing to what column at other one), but try something similar (modification needed to meet You DB structure) - now lets assume both tables have related column called event_id:
$SQL = "SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106,
richiesta_ccnl_107, coop_va_109, nome_pdv_110,
indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22 cvistlsp22
LEFT JOIN civicrm_event ce ON ce.event_id = cvistlsp22.event_id
WHERE ce.title_en_US='".mysql_real_escape_string($_GET["titles"])."'";
civicrm_value_informazioni_su_tute_le_schede_p_22 table name is very long and You will not be able to create a table with such long name in other DBMS (e.g. ORACLE), so try to make it shorter while still self-describing...
If You want to join tables they have to have a relation, read more about relations and how to use them here: http://net.tutsplus.com/tutorials/databases/sql-for-beginners-part-3-database-relationships/
You are retrieving the data from table civicrm_value_informazioni_su_tute_le_schede_p_22 in your query while the where clause you are adding, refers to the table civicrm_event. You need to add this new table in the from clause and do a join among the two tables using some common key. Example below:
$SQL = "
SELECT distretto_108, provinca_113, regioni_116, tipologia_pdv_106, richiesta_ccnl_107, coop_va_109, nome_pdv_110, indirizzo_pdv_111, localita_112
FROM civicrm_value_informazioni_su_tute_le_schede_p_22
JOIN civicrm_event ON civicrm_value_informazioni_su_tute_le_schede_p_22.ID_PK = civicrm_event.ID_FK
WHERE civicrm_event.title_en_US='".addslashes($_GET["titles"])
";
You need to replace the ID_PK and ID_FK with the relevant Primary and Foreign Keys that bind the tables together.
Please note using query params like that is not recommended. Please read PHP Documentation here for more explanation.
I have a table for users. But when a user makes any changes to their profile, I store them in a temp table until I approve them. The data then is copied over to the live table and deleted from the temp table.
What I want to achieve is that when viewing the data in the admin panel, or in the page where the user can double check before submitting, I want to write a single query that will allow me to fetch the data from both tables where the id in both equals $userid. Then I want to display them a table form, where old value appears in the left column and the new value appears in the right column.
I've found some sql solutions, but I'm not sure how to use them in php to echo the results as the columns in both have the same name.
Adding AS to a column name will allow you to alias it to a different name.
SELECT table1.name AS name1, table2.name AS name2, ...
FROM table1
INNER JOIN table2
ON ...
If you use the AS SQL keyword, you can rename a column just for that query's result.
SELECT
`member.uid`,
`member.column` AS `oldvalue`,
`edit.column` AS `newvalue`
FROM member, edit
WHERE
`member.uid` = $userId AND
`edit.uid` = $userId;
Something along those lines should work for you. Although SQL is not my strong point, so I'm pretty sure that this query would not work as is, even on a table with the correct fields and values.
Here is your required query.
Let suppose you have for example name field in two tables. Table one login and table 2 information. Now
SELECT login.name as LoginName , information.name InofName
FROM login left join information on information.user_id = login.id
Now you can use LoginName and InofName anywhere you need.
Use MySQL JOIN. And you can get all data from 2 tables in one mysql query.
SELECT * FROM `table1`
JOIN `table2` ON `table1`.`userid` = `table2`.`userid`
WHERE `table1`.`userid` = 1
I am currently working on a school system where we have a parent course and a child course (meta_courses in Moodle).
So, we have a table mdl_course_meta and it has 3 fields. Id, parent_course and child_course.
My problem is that a parent course can have many child courses so that means, for example, a parent_course = 50 can appear two times in the table which means it has 2 child courses. I just want to be able to find all the parent courses without it returning the same value twice or more times. I'm currently using this query right now which obviously doesn't do what I want:
$q = "SELECT * FROM mdl_course_meta";
I am working with PHP as well by the way.
Thanks a lot.
SELECT DISTINCT parent_course from mdl_course_meta
That should do it if you just want the course names. One thing to keep in mind, if you want other fields this is not going to work the way you want it to(how would it know which record to choose if there are multiple records with the same parent_course and you only want one).
This approach can only be used if you only want to return the parent_courses without duplicates.
DISTINCT helps to eliminate duplicates. If a query returns a result that contains duplicate rows, you can remove duplicates to produce a result set in which every row is unique. To do this, include the keyword DISTINCT after SELECT and before the output column list.
$q = "SELECT DISTINCT parent_course FROM mdl_course_meta";
If you don't want duplicate values in a single column, use GROUP BY parent_course.
In this way you are free to select any column.
If you only want distinct values for a particular column column, then you can use GROUP BY:
SELECT *
FROM mdl_course_meta
GROUP BY parent_course
The values in the other columns will be arbitrary. This will work in MySQL 5.x.
MySQL 4.x won't let you be arbitrary, so you can't mix aggregate and non-aggregate columns. Instead, you'd have to do something like this, which gets a bit complicated:
SELECT MAX(col1), MAX(col2), parent_course, MAX(col4), ...
FROM mdl_course_meta
GROUP BY parent_course
This way, the values aren't arbitrary. You've specified the ones you want.
I currently have a page that displays player information from one table named "tblplayers". The query I am currently using is:
$result = mysql_query("SELECT * FROM tblPlayers WHERE lng_RecordID_PK = '".$playerid."' ");
I have a second table named "tblMatches" containing match results for the players. I want the recordset to include the rows from "tblMatches" WHERE "P1_ID" OR "P2_ID" is equal to the "lng_RecordID_PK" field from "tblPlayers".
How can I revise my $result query so that it returns:
one row from tblPlayers
multiple rows from tblMatches
???
Thanks for helping me out.
That's called a 'join':
SELECT tblPlayers.*, tblMatches.*
FROM tblPlayers
LEFT JOIN tblMatches ON Ing_RecordID_PK IN (P1_ID, P2_ID)
You are asking about joining two tables where the second table potentially has multiple records for each one in the first table. This is a one-to-many or 1:N join, and most often done using a LEFT JOIN meaning you want everything in the "left" table, and all the records that match from the "right" table, and that you may have some records on the "left" side with no matches.
Your query would look like this:
SELECT *
FROM tblPlayers
LEFT JOIN tblMatches
ON (tblPlayers.lng_RecordID_PK = tblMatches.P1_ID
OR tblPlayers.lng_RecordID_PK = tblMatches.P2_ID)
WHERE tblPlayers.lng_RecordID_PK = #PlayerID;
Bits of advice:
Avoid selecting all columns (*) and instead select just those that you need for the query.
Consider using parameterized queries to avoid SQL injection attacks. If your variable were to be submitted or altered maliciously, it could result in compromised data or security. (See PHP Data Objects for example.)
There is no way to get rows from two different tables in the way you are describing. You could not get a row from one table, and two rows from another one. What you could is do two separate queries, or use a JOIN statement to join the two tables together, and then receive results from the resulting joined table. If you provide more information about your table structure I am sure more help can be given.