QGIS Select by Attribute – How to Select Items in Attribute Column Based on Another Layer

attribute-tablefields-attributeslayersqgisselect-by-attribute

I have the items in my data attribute table, which were selected. I want to make the object with the same value be selected in the attribute table, which belongs to another layer. In both cases, the considered column is called "new_name".

If for instance the "new_name" value has been selected in the left attribute table I need exactly the same value to be selected in the other attribute table.

enter image description here

How can I make a selection such as this?

Best Answer

I can suggest a PyQGIS solution.

Proceed with Plugins > Python Console > Show Editor and paste the script below

from qgis.core import QgsProject

layer1 = QgsProject.instance().mapLayersByName('Final cellsites')[0]
layer2 = QgsProject.instance().mapLayersByName('Lighting columns')[0]

field1 = "new_name"
field2 = "new_name"

selected_features = [feat[field1] for feat in layer1.selectedFeatures()]

selected_attributes = f'({selected_features[0]})' if len(selected_features) == 1 else tuple(selected_features)

expression = f'"{field2}" in {selected_attributes}'

layer2.selectByExpression(expression)

Press Run script run script and get the output that will look like

example


References:

Related Question