I'm working with the InnoDB version of MySQL's world database (available here) and am trying to fetch a list of the countries of South America and their capitals. In my mind, the query should look like this:
SELECT `Country.Name` as `CountryName`, `City.Name` as `CityName`
FROM `Country`, `City`
WHERE `Continent` = 'South America' AND `ID` = `Capital`;
But that one gives error #1054 - Unknown column 'Country.Name' in 'field list', even though the table Country does have the field Name.
Why isn't MySQL finding the fields I want? How do I change the query to make it find them?
Let me know if I need to provide more information for you to be able to help me.
If you quote identifiers, do not surround the inner dot with backticks.
SELECT
`Country`.`Name` AS CountryName,
`City`.`Name` AS CityName
If you quote around the inner dot, it will be assumed to be inside the column name, rather than a separator between the table name and column name -- you have a column named Name, but not a column called Country.Name. In this case, however, it is unnecessary to quote any of the identifiers since none of them are MySQL reserved keywords.
Try modifying your back ticks.
SELECT
`Country`.`Name` as `CountryName`,
`City`.`Name` as `CityName`
FROM `Country`, `City`
WHERE `Continent` = 'South America' AND `ID` = 'Capital';
Do not put them around the entire table.column, but around them individually with the period between them.
Also capitol should be single quotes and not back ticks.
This appears to be a syntax issue:
Try using this instead:
`Country`.`Name`
country.name (in ticks) would be the name of the field when what your after is
`country`.`name`
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
Im trying to write a query in MySQL however one fo my column names is 'comment' however when entered into a WHERE clause it shows up bold and doesn't get used as a column name does anyone know how to change that?
this is the query
SELECT DISTINCT propertyNo from Viewing
WHERE comment IS NULL
UNION
SELECT propertyNo FROM PropertyForRent
WHERE rent < 600
ORDER BY propertyNO ASC;
You need to quote it:
WHERE `comment` IS NULL
This is covered in the Schema Object Names sections of the MySQL 5.7 Reference Manual.
Always use backticks and quotation marks when you write your SQL.
With ` you write variable names
With ' you write variable values
For example
SELECT * FROM `test` WHERE `x` = 'blahblah'
COMMENT is a keyword in MySQL. See: https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-C
That's why your editor shows it as bold. You can escape this by using back ticks:
SELECT DISTINCT `propertyNo` from `Viewing`
WHERE `comment` IS NULL
Try to always use back ticks when referring to columns or table names. More info on that subject: https://dba.stackexchange.com/questions/23129/benefits-of-using-backtick-in-mysql-queries/23130
I have a table, one of the columns contains a text values, some of which are comma separated string, like this:
Downtown, Market District, Warehouse District
I need to modify my query to see is a given value matches this column. I decided that using IN() is the best choice.
SELECT *
FROM t1
WHERE myValue IN (t1.nighborhood)
I am getting spotty results - sometimes I return records and sometimes not. If there's a value in t1.nighborhood that matches myValue, I do get data.
I checked and there are no MySQL errors. What am I missing?
You can use FIND_IN_SET() to search a comma-delimited list:
SELECT *
FROM t1
WHERE FIND_IN_SET(myValue, REPLACE(t1.nighborhood, ', ', ','));
The REPLACE() is necessary to remove the extra spaces.
Another solution is to use regex to match your search value surrounded by commas if necessary:
SELECT *
FROM t1
WHERE t1.nighborhood REGEXP CONCAT('(^|, )', myValue, '(, |$)');
In general, it's bad design to store distinct values in a single column. The data should be normalized into a related table with a foreign key.
I have a module that generates a csv file to feed data to a third party, but want to modify it to use for another company. The column names they want for the csv are different to the ones set up in the current module, such as Product Name instead of product__name.
An example of the sql in the original mod is:
$query = 'select
p.products_id as uuid,
t.type_name as product__type,
d.products_name as product__name,
d.products_description as product__description,
d.products_url as product__url,
d.products_viewed as product__viewed_count,
p.products_quantity as product__quantity,
p.products_model as product__model,
p.products_image as product__image
.....
I tried to change d.products_name as product__name, to d.products_name as Product Name, but it gives me an sql error.
Is there any easy solution to this without having to rewrite the whole module?
since you are using space for your identifier, you should quote them, like so:
d.products_name as `Product Name`
see http://dev.mysql.com/doc/refman/4.1/en/identifiers.html
You can use backquotes to enclose your aliases.
d.products_name as `Product Name`
This is useful to output column names that are mysql keywords or column names with spaces.
Try this:
d.products_name as 'Product Name',
When you want an alias with spacing, you have to treat it as a string.
d.products_name as 'Product Name',
I can't seem to get the substring_index() to work:
I have created a simple table as follows:
CREATE TABLE ContactList(
cont_id int(11) NOT NULL AUTO_INCREMENT,
last_name varchar(30),
first_name varchar(20),
interests varchar(100),
PRIMARY KEY(cont_id));
I then populated the ContactList table as follows:
INSERT INTO ContactList (last_name, first_name, interests)
VALUES
('Murphy', 'Dave', 'Golf, Pets, Basketball'),
('Murphy', 'Ben', 'Pets, Gym, Basketball'),
('Finn', 'Belinda', 'Pets, Tennis, Knitting'),
('Murphy', 'Steve', 'Pets, Archery, Fishing');
I ran a quick SELECT to ensure the data was entered correctly:
SELECT * FROM ContactList;
Then I ran the following query:
SELECT * FROM ContactList
WHERE last_name = 'Murphy'
AND SUBSTRING_INDEX(interests, ',' ,1) = 'Pets';
I was expecting to get two records back (which I did for Ben & Steve), however, for the 'Interests' column I was assuming I should only get one interest back if it equaled 'pets' (due to the substring_index) however, I got all interests back. How can I use the SUBSTRING_INDEX() to run the query and only get the first interest listed back for each record if it says 'Pets'?
BTW I am using MySQL Version 5.5.24 and I know the Interests would be best suited in their own table - I just want to see why substring_index is not picking the first item from the list if it equals 'pets'.
Thanks for any input,
Andy R ;-)
You're using SUBSTRING_INDEX in the WHERE clause, which determines which rows to include. That's good, but you also need to use it in the SELECT clause, which determines which columns to include.
Try this:
SELECT
last_name,
first_name,
SUBSTRING_INDEX(interests, ',' ,1) AS FirstInterestInList
FROM ContactList
WHERE last_name = 'Murphy'
AND SUBSTRING_INDEX(interests, ',' ,1) = 'Pets';
Although substring_index() will work for the first element, you really want find_in_list():
SELECT last_name, first_name, SUBSTRING_INDEX(interests, ',' ,1) AS FirstInterestInList
FROM ContactList
WHERE last_name = 'Murphy' and
find_in_set('pets', interests) = 1
The advantage of find_inset() is that it will work for arbitrary positions.
Just as a note, though, your delimiter is ', '. For find_in_set() to work best, you should have no space after the column.
Also, if you are doing queries like this, you should fix your data structure. It really wants a table called something like ContactInterests which contains one row for each contact and each interest.
Currently I'm making my website application to validate the suburb values and ensure it exsits in the database data.
Here is my MySQL table
CREATE TABLE IF NOT EXISTS `postcodeTable` (
`id` int(11) NOT NULL,
`postcode` varchar(50) NOT NULL,
`suburb` text NOT NULL,
`state` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The user input 2 variables which are State and Suburb variable.
Here is my SQL statement to check if the row exists:
"select * from postcodeTable where state='".$state."' and suburb LIKE '%".$suburb."%'";
Here is my sample table data
Row1 id:1 postcode:3794 suburb: BANGHAM,BORDERTOWN,CANNAWIGARA,LOWAN, state: SA
Row2 id:2 postcode:6627 suburb: CANNA, state: WA
When a user input suburb CANNA and state SA it matches with the MySQL statement which is incorrect.
It matches because the LIKE statement because 'CANNA' word in CANNAWIGARA suburb name.
Which is incorrect because CANNA suburb only exist in WA state.
Is there a way to make the LIKE statement smarter which can go through the suburb string and ensure it matches the whole suburb name only?
Thanks so much in advance!
The problem here is your database schema : you should not store several suburbs in a single field of the postcodeTable table.
Instead, you should have one suburbs table, that would store one suburb per line, with a foreign key that points to the corresponding postcodeTable row.
Your postcodeTable table would be :
id
postcode
state
And your suburbs table would be :
id_suburb
id_postcode : foreign key to postcodeTable
name
Then, as suburbs.name would contain the exact name of one suburb, you wouldn't have to use like %...% anymore : you'd just have to use suburbs.name = '...'
And here's an idea of what your SQL query would look like :
select postcodeTable.*
from postcodeTable
inner join suburbs on suburbs.id_postcode = postcodeTable.id
where
suburbs.name = 'CANNA'
and postcodeTable.state = 'SA'
You could try regular expression matching. But I think it would be better to normalize your database. That is, split the suburbs off in a separate table, with a key pointing to the postcode table. Then you could do:
SELECT * FROM postcodeTable p
LEFT JOIN suburbTable s ON s.postcode_id = p.id
WHERE p.state = 'SA' AND s.name = 'CANNA';
Which should return zero rows.
If you need to search for exact comparisons, rather use
"select * from postcodeTable where state='".$state."' and suburb = $suburb
or drop the "%" at the back.
Have a look at the SQL Wildcards available: http://www.w3schools.com/sql/sql_wildcards.asp
If you don't want to modify your tables as people are suggesting, try:
"select * from postcodeTable where state='".$state."' and suburb LIKE '%".$suburb."%,'";
It will solve some problems, but not all of them.
Try:
$query = "select * from postcodeTable
where state='".$state."' and suburb REGEXP '(^|,)".$suburb."(,|$)'";
But as many others did, I strongly suggest you to normalize your schema.
Thanks for the responses!
Silly me I just realised if I just add a comma to the suburb field, it would solves the problem.
Since "comma" symbol in my suburb string means end of surburb word.
Cheers!
Thanks for the quick responses!
Silly me I just realised if I just add a comma to the suburb input field, it would solve the problem.
Since "comma" symbol in my suburb string means end of surburb word.
Thanks for your advices! I would normalise my Postcode table when I get the chance.
Cheers!