I have mysql table tmp with columns pid,city,state,country. I write queries so i can find matching city,state or country, and pid is field that helps me load another table.
The thing is, there is always two rows with same pid, and sometimes (when WHERE find matching city state or country in both), i display data from additional table twice unnecessarily.
So i need to select something like:
SELECT * FROM tmp DISTINCT pid WHERE city='test'
I have no idea how to search solution (i searched here on stackoverflow, but no luck).
Also, there will be a lot of searching in this table, so if there is multiple solutions i would prefer one that is faster.
Thanks
Please try the following SQL statement:
SELECT DISTINCT pid FROM tmp WHERE city='test'
try this
SELECT DISTINCT pid,field1,field2 FROM tmp WHERE city='test'
$keyword="0";
$query = "SELECT DISTINCT titel,id FROM xyz ORDER BY titel ASC ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
if($keyword!==$row["titel"])
{
$keyword=$row["titel"];
echo $keyword;
}
}
Related
I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}
I can not find a proper answer to this question. I have a very simple code for making a query in mysql to select the row with the maximum value in a determined column (called popularity) from a table (called comments). Every row has a column named comment_id
here is the code:
$connect_error = 'Sorry, try again, there was a connection error';
$con = mysqli_connect('localhost','user_name','password') or die($connect_error);
mysqli_select_db($con, 'database') or die($connect_error);
$result = mysqli_query($con, "SELECT MAX(`popularity`) FROM `comments`");
while ($row = mysqli_fetch_assoc($result)) {
$most_popular = $row['comment_id'];
}
echo "most popular is: $most_popular";
mysqli_free_result($result);
mysqli_close($con);
the screen does not show a proper result. Can someone give me an advice in this regard?
Thank you
You are looking to display the comment_id field, but you don't have that in your SELECT query. You are only selecting the max popularity value, and nothing else.
Try this for your query:
SELECT comment_id FROM comments ORDER BY popularity DESC LIMIT 1
This is sorting your comments by popularity, and then just picking the top one.
Of course you can easily change that to select more columns or even a SELECT * if you want to be able to display other values in this record.
To select the row with max 'popularity' column use this query;
$result = mysqli_query($con, "SELECT * FROM `comments` ORDER BY `popularity` DESC LIMIT 1");
In case you want all sorted by popularity remove the LIMIT 1...
You need
SELECT MAX(`popularity`) AS comment_id FROM `comments`
This will give the column the correct name for the associated array.
You are trying to read the result from a column named comment_id when the result from your query will be named MAX(popularity)
Run this query in mysql "SELECT MAX(popularity) FROM comments" first.The output of this gives you the index to use with $row[index] ie first row which in this case the index will be popularity else just change $row[content_id] to $row[popularity]
I am very new to using PHP so I am asking for some help. I have this code which works fine (I got it online from somewhere).
$data = mysql_query("SELECT * FROM products")
or die(mysql_error());
print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
print "<tr>";
print "<th>title:</th> <td>".$info['title'] . "</td> ";
print "<th>info:</th> <td>".$info['information'] . " </td></tr>";
}
print "</table>";
But what PHP would I use to pull just one cell? For example, I have 9 items in my db with productIDs how could I call just the name or price or description for that particular product?
Thanks in advance.
It sounds like you want a particular row, in which, case you would just changes your query to filter for some specific value that identifies the row. THis might look something like this:
SELECT * FROM products WHERE product_id = ?
Where ? is the known product_id value that you want to receive the full record for.
Also, since you are just learning, I should point out that you should not learn to use mysql_* functions. They are deprecated. Learn mysqli or PDO for interacting with MySQL.
To obtain just one cell try the following:
SELECT CellName FROM TableName Where productId = x
So to get the price you would do:
SELECT price FROM products WHERE productid=x
Where productid equals the specific product you talked about.
if you want to understand a bit more mysql I advise you to go to PhpMyAdmin and try those and think about the result:
SELECT * FROM products;
SELECT title, information AS lol FROM products;
SELECT title, count(*) AS count FROM products;
SELECT * FROM products WHERE title = 'XXXX';
SELECT *, count(*), CHAR_LENGTH(title) FROM products;
SELECT title AS lol FROM products;
you will understand better the query language i thinks.
please read this chapter http://dev.mysql.com/doc/refman/5.0/en/examples.html. it'll really help you.
I just want to say, you can retrieve any columns(s) in any condition column
SELECT column_name(s) FROM products WHERE colmnm_name = ?
I'm trying to add a single column in a db query result. I've read about the SUM(col_name) as TOTAL, GROUP BY (col_name2).
But is there a way i can only SUM the column without any GROUPing? I a case whereby all col_name2 are all unique.
For example... I have a result with the following col headers:
course_code
course_title
course_unit
score
grade
Assuming this have 12 rows returned into an HTML table. Now i want to perform SUM() on all the values (12 rows) for the column course_unit, in other to implement a GPA school grading system.
How can i achieve this.
Thanks.
SELECT SUM(col_name) as 'total' FROM <table>
GROUP BY is required only if you want to sum subsets of the rows in the table.
You can find sum or any aggregate db functions (such as count, avg, etc) for most cases without using group clause. Your sql query may look something like this:
SELECT SUM(course_unit) as "Total" FROM <table_name>;
As comments below have already pointed out: SELECT SUM(course_unit) AS total FROM your_table;. Note that this is a separate query to the one with which you retrieve the table data.
This does it in php. I'm not sure how to do it with pure sql
$query = "SELECT * FROM table";
$result = mysql_query($query);
$sum = 0;
while($row = mysql_fetch_assoc($result))
{
$sum+= intval($row['course_unit']);
}
echo $sum;
SELECT
course_code,
course_title,
course_unit,
score, grade,
(select sum(course_unit) from TableA) total
from TableA;
When I'm selecting from multiple tables that share column names is there a way I can return both, but define which one I want to select the data from?
For instance:
Both tables contain "date" columns, and I want to use both, but I would like to avoid having to rename each column that has duplicate names.
$query = mysql_query("SELECT * FROM posts, comments"); //(SELECT * is just for example)
while($row=mysql_fetch_array($query))
{
$postDate = $row['date']; //I would like to be able to do something like:
//$postDate = $row['posts']['date']; OR $row['posts.date'];
//of course it's all in an array now, jumbled up.
$commentDate = $row['date'];
}
You need to alias the duplicate column names in your query if you want both, eg
SELECT p.date AS postDate, c.date AS commentDate
FROM posts p, comments c
Then use the aliases to retrieve the values
$postDate = $row['postDate'];
$commentDate = $row['commentDate'];
FYI, it's almost never a good idea to SELECT *, especially when multiple tables are involved. You should always try to be specific about the columns added to your SELECT clause
The best way to do this is to specify the fields in the query itself, giving aliases to them:
SELECT posts.date postDate, comments.date commentDate FROM posts, comments;
It's generally frowned upon to use SELECT *. You end up with code that's a little less stable. By specifying the exact fields, and the aliases of those fields, you are less prone to bugs that might arise from changes to the database schema, etc.
Just add aliases...btw, you should never use SELECT * FROM ...
$query = mysql_query("SELECT posts.date as pdate, comments.date as cdate FROM posts, comments");
while($row=mysql_fetch_array($query))
{
$postDate = $row['pdate'];
$commentDate = $row['cdate'];
}